package org.example.netty.test;

import io.netty.channel.Channel;
import org.example.netty.constant.MessageType;
import org.example.netty.handler.message.BusinessMessageTypeHandler;
import org.example.netty.handler.message.MessageHandlerFactory;
import org.example.netty.model.CustomMessage;
import org.example.netty.model.ExtendedChannelContext;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultMessageHandlerFactory implements MessageHandlerFactory {

    private static ConcurrentHashMap<Byte, BusinessMessageTypeHandler> hashMap=new ConcurrentHashMap<>();
    static {
        hashMap.put(MessageType.STRING_REQUEST,new StringResponseMessageTypeHandler());
        hashMap.put(MessageType.STRING_REPSONSE,new StringRequestMessageTypeHandler());
    }

    @Override
    public BusinessMessageTypeHandler getHandler(byte type) {

        return hashMap.get(type);
    }
    private static class StringRequestMessageTypeHandler implements BusinessMessageTypeHandler{

        @Override
        public void handler(CustomMessage requestMessage, ExtendedChannelContext extendedChannelContext) {
            System.out.println(new String(requestMessage.getContent()));
            String msg="收到";
            byte[] content = msg.getBytes(StandardCharsets.UTF_8);
            CustomMessage response = new CustomMessage(
                    requestMessage.getMagic(),
                    requestMessage.getVersion(),
                    requestMessage.getSerializeAlgo(),
                    0,  // 明确设置保留字段
                    MessageType.HEARTBEAT_RESPONSE,
                    requestMessage.getRequestId(),
                    content.length,
                    content
            );
            extendedChannelContext.sendResponse(response);
        }
    }
    private static class StringResponseMessageTypeHandler implements BusinessMessageTypeHandler{

        @Override
        public void handler(CustomMessage requestMessage, ExtendedChannelContext extendedChannelContext) {
            Channel channel = extendedChannelContext.getChannel();
            long requestId = requestMessage.getRequestId();
            extendedChannelContext.completeRequest(requestId,requestMessage);
        }
    }
}
